const path = require('path');
const fs = require('fs');
const { app } = require('electron');

export function resloveFilePath(filePath) {
  if (app && process.env.NODE_ENV !== 'development') {
    return path.join(app.getPath('userData'), filePath);
  } else {
    return path.join(__dirname, filePath);
  }
}

export function checkFile(filePath) {
  const fileAbsolutePath = resloveFilePath(filePath);
  return { exist: fs.existsSync(fileAbsolutePath), fileAbsolutePath };
}

export function mkFile(filePath, data) {
  const { exist, fileAbsolutePath } = checkFile(filePath);
  if (!exist) {
    fs.writeFileSync(fileAbsolutePath, data, {
      flags: 'w',
      encoding: 'utf8',
    });
  }
}

export function mkDir(filePath) {
  const { exist, fileAbsolutePath } = checkFile(filePath);
  if (!exist) {
    fs.mkdirSync(fileAbsolutePath);
  }
}

export function readFileSync(filePath) {
  const { exist, fileAbsolutePath } = checkFile(filePath);
  if (exist) {
    return fs.readFileSync(fileAbsolutePath, {
      flags: 'r',
      encoding: 'utf8',
    });
  }
  return null;
}

export function saveFile(filePath, data) {
  if (typeof data === 'string') {
    const { exist, fileAbsolutePath } = checkFile(filePath);
    if (exist) {
      fs.writeFile(fileAbsolutePath, data, { flags: 'w', encoding: 'utf8' }, (err) => {});
    }
  }
}

export const imageFileFilter = (req, file, callback) => {
  if (!file.originalname.match(/\.(jpg|jpeg|png|gif|svg)$/)) {
    return callback(new Error('请上传jpg、jpeg、png、gif、svg格式的图片'), false);
  }
  callback(null, true);
};

export const editFileName = (req, file, callback) => {
  const name = file.originalname.split('.')[0];
  const fileExtName = path.extname(file.originalname);
  const randomName = new Date().getTime() + Math.floor(Math.random() * 1000);
  callback(null, `${name}-${randomName}${fileExtName}`);
};
